﻿using CommandLib;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using SignalrChat.Models;

namespace SignalrChat
{
    /// <summary>
    /// 统一异常处理过滤器
    /// </summary>
    public class CustomerExceptionFilter : IAsyncExceptionFilter
    {
        /// <summary>
        /// 异常拦捷
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public Task OnExceptionAsync(ExceptionContext context)
        {
            //获取当前登陆帐号
           
            if (context.ExceptionHandled == false)
            {
                var rotes = context.ActionDescriptor.RouteValues;
                var actionUrl = $"/{rotes["controller"]}/{rotes["action"]}";
                var parmData = context.ActionDescriptor.Parameters;               
                context.Result = new ContentResult
                {
                    Content = context.Exception.Message,
                    StatusCode = StatusCodes.Status500InternalServerError,
                    ContentType = "application/json;charset=utf-8"
                };
                AsyncLoger.AddErrorLog(new
                {
                    action = actionUrl,
                    parm = parmData,
                    error = context.Exception?.Message
                });
            }
            //异常已处理了
            context.ExceptionHandled = true;

            return Task.CompletedTask;
        } 
    }
}
